import datetime
import os

import pymysql
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

from src import app

pymysql.install_as_MySQLdb()

# username = "test_user"
# password = "test_password"

username = 'root'
password = '123456'
host = 'localhost'
port = 3306
database_name = 'easy_test'
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql://{username}:{password}@{host}:{port}/{database_name}"

db = SQLAlchemy(app)
migrate = Migrate(app, db)

engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])

SessionLocal = sessionmaker(bind=engine)

db_session: Session = SessionLocal()


def create_tables():
    # 导入所有model类
    import importlib
    import inspect
    import pkgutil

    # 获取baseapp/model目录的路径
    models_path = os.path.dirname(os.path.abspath(__file__))

    # 遍历model目录下的所有模块
    for _, name, _ in pkgutil.iter_modules([models_path]):
        # 动态导入模块
        module = importlib.import_module(f"src.baseapp.model.{name}")

        # 获取模块中所有的类
        for _, obj in inspect.getmembers(module, inspect.isclass):
            # 检查类是否是CustomDbModel的子类，但不是CustomDbModel本身
            if issubclass(obj, CustomDbModel) and obj != CustomDbModel:
                # 这里不需要做什么，只要导入了类就可以
                pass

    with app.app_context():
        db.create_all()


class CustomDbModel(db.Model):
    # 创建时间
    create_time = db.Column(db.DateTime, default=datetime.datetime.now)

    # 更新时间
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)

    # 0表示未删除，1表示已删除
    is_delete = db.Column(db.int, default=0)

    def save(self):
        try:
            db.session.add(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise

    def add_all(self):
        try:
            db.session.add_all(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}
